package com.hmall.search.mq;

import com.hmall.common.client.ItemClient;
import com.hmall.item.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.service.impl.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * MQ消息监听器
 */
@Component
@Slf4j
public class ItemListener {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SearchService searchService;


    /**
     * 监听新增/上架商品(修改商品之前先下架，所以不用监听修改操作)
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hmMall.shelvesUp.item-queue"),  //队列名称
            exchange = @Exchange(
                    name = "hmMall-item-exchange",  //交换机名称
                    type = ExchangeTypes.DIRECT), //交换机类型
            key = {"shelves.up"}//主题名称
    ))
    public void listenInsertOrUpdateItem(Long id) throws IOException {
        log.info("接收到消息up：{}" , id);
        //1 根据id查询商品信息，加了拦截器之后此处远程调用就走不通了，因为feign远程调用没有携带authorization请求头
        Item item = itemClient.selectById(id);
        //2 调用service，新增或者修改文档
        ItemDoc itemDoc=new ItemDoc(item);
        searchService.addOrUpdateItemDoc(itemDoc);
    }

    /**
     * 监听下架商品(删除商品之前先下架，所以不用监听删除操作)
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hmMall.shelvesDown.item-queue"),  //队列名称
            exchange = @Exchange(
                    name = "hmMall-item-exchange",  //交换机名称
                    type = ExchangeTypes.DIRECT), //交换机类型
            key = {"shelves.down"}//主题名称
    ))
    public void listenDeleteItemDoc(Long id) throws IOException {
        log.info("接收到消息down：{}" , id);
        //1 根据id删除文档
        searchService.deleteItemDoc(id);
    }
}
